<template>
  <div style="padding: 0 2px">
    <template v-if="auth === 'edit'">
      <a-tree-select style="width: 100%" :size="size"
                     showSearch treeNodeFilterProp="title" searchPlaceholder="请输入单位名称"
                     treeDefaultExpandAll
                     :replaceFields="{children:'children', title:'departName', key:'id', value: 'id' }"
                     :placeholder="fieldConfig.placeholder"
                     :multiple="true"
                     allowClear
                     :treeData="dataItems"
                     :dropdownStyle="{maxHeight:'200px',overflow:'auto'}"
                     v-model="innerValue"
      >
      </a-tree-select>
    </template>
    <template v-else>
      <span style="padding: 5px;">
        {{ title || value }}
      </span>
    </template>
  </div>
</template>
<script>
import {createProps} from '@/utils';
import { getCurrentUserDeparts } from '@api/api'
import { isArray } from 'ant-design-vue/lib/_util/vue-types/utils'

export default {
  name: 'UnitsField',
  props: {
    fieldConfig: createProps(Object),
    value: {
      type: [Number, String],
      default: undefined
    },
    title: createProps(String),
    auth: createProps(String),
    size: createProps(String, 'default')
  },
  data() {
    return {
      departTree: null
    }
  },
  methods: {
    loadTreeData() {
      getCurrentUserDeparts().then(res => {
        if (res.success) {
          this.departTree = res.result.list
        }
      })
    },
    getTitlesString(val) {
      if (!val) return undefined
      if (isArray(val)) {
        return this.dataItems.filter(item => val.indexOf(item.id) !== -1)
          .map(i => i.departName).toString()
      } else {
        return this.dataItems.filter(item => val === item.id)
          .map(i => i.departName).toString()
      }
    },
    handleDepartShowData(checkedKeys, tree, disabled = false) {
      if (checkedKeys.length > 0) {
        let temp = []
        checkedKeys.forEach(key => {
          if(!key || !tree) return
          const index = tree.findIndex(e => e.value == key)
          if (index >= 0) {
            temp.push(tree[index])
          }
        })
        // 若为true则第一级disabled
        if (disabled) {
          temp.forEach(e => e.disabled = true)
        }
        return temp
      } else {
        return []
      }
    },
  },
  computed: {
    innerValue: {
      get() {
        if (this.value&&this.value.length) {
          return this.value.split(',')
        }
        return undefined
      },
      set(val) {
        this.$emit('update:value', val && val.toString() || undefined)
        this.$emit('update:title', this.getTitlesString(val))
      }
    },
    dataItems() {
      return this.departTree
    }
  },
  watch: {
    auth: {
      immediate: true,
      handler(val) {
        val==='edit' && this.loadTreeData()
      }
    }
  }
};
</script>